package github.sf.fw.tools;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExtClassLoader extends URLClassLoader {
    private final String classLoaderName;

    public ExtClassLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
        this.classLoaderName = "ExtClassLoader";
    }

    public ExtClassLoader(String classLoaderName, URL[] urls, ClassLoader parent) {
        super(urls, parent);
        this.classLoaderName = classLoaderName;
    }


    public ExtClassLoader(String rootDir) {
        this(rootDir, Thread.currentThread().getContextClassLoader());
    }

    public ExtClassLoader(String rootDir, ClassLoader parent) {
        super(new URL[]{}, parent);
        this.classLoaderName = "ExtClassLoader";
        if (rootDir == null || "".equals(rootDir)) {
            return;
        }
        Path path = Paths.get(rootDir);
        //防止后续无意义的遍历查询
        if (path.toFile().exists()) {
            File[] files = path.toFile().listFiles();
            if (files != null) {
                //防止后续无意义的遍历查询
                //只扫描指定目录的第一层
                for (File file : files) {
                    if (file.isFile() && file.getName().endsWith(".jar")) {
                        URL url;
                        try {
                            url = new URL("file:///" + file.getAbsolutePath());
                            addURL(url);
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }

    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        return super.loadClass(name, resolve);
    }

    public String getClassLoaderName() {
        return classLoaderName;
    }
}
